<template>
  <div class="h-full w-full">
    <div class="px-4 py-3" style="border-bottom: 1px solid #4f4f4f; font-weight: 450" v-if="taskRoute">
      <div class="flex justify-between items-center" style="height: 34px">
        <span v-if="taskRoute">任务计划库</span>
        <span v-if="taskRoute" class="flex items-center">
          <el-button>
            <Plus />
            <router-link :to="{ name: ERouterName.CREATE_PLAN }"> 新建任务 </router-link>
          </el-button>
        </span>
      </div>
    </div>
    <template v-if="!taskRoute">
      <router-view />
    </template>
    <div v-else>
      <div class="scrollbar" :style="{ height: scorllHeight + 'px' }">
        <div v-if="onlineDocks.data.length === 0" style="height: 150px; color: white" class="flex justify-center">
          <a-empty :image="noData" :image-style="{ height: '100px' }" />
        </div>
        <div v-else class="fz12 px-3 py-3" style="color: white">
          <div v-for="dock in onlineDocks.data" :key="dock.sn" class="online px-2 py-2 hover:border-[1px] hover:border-[#e6e6e6]">
            <div class="flex justify-between w-full px-2 items-center h-9 text-base" style="border: 1px solid #595959">
              <a-tooltip :title="`${dock.gateway.callsign} - ${dock.callsign ?? '无人机'}`">
                <div class="truncate w-52">{{ dock.gateway.callsign }} - {{ dock.callsign ?? '无人机' }}</div>
              </a-tooltip>
            </div>
            <div>
              <div class="mt5 flex" style="border: 1px solid #595959">
                <div class="flex-row flex-1 items-center">
                  <span class="ml5 mr5 flex items-center"><RobotOutlined /></span>
                  <div
                    class="font-bold text-hidden"
                    style="max-width: 100px"
                    :style="
                      dockInfo[dock.gateway.sn] && dockInfo[dock.gateway.sn].basic_osd?.mode_code !== EDockModeCode.Disconnected
                        ? 'color: #00ee8b'
                        : 'color: red;'
                    "
                  >
                    {{
                      dockInfo[dock.gateway.sn]
                        ? EDockModeCodeStatus[dockInfo[dock.gateway.sn].basic_osd?.mode_code]
                        : EDockModeCodeStatus[EDockModeCode.Disconnected]
                    }}
                  </div>
                </div>
              </div>
              <div class="mt5 flex" style="border: 1px solid #595959">
                <div class="flex-row flex-1 items-center">
                  <span class="ml5 mr5 flex items-center"><RocketOutlined /></span>
                  <div
                    class="font-bold text-hidden"
                    style="max-width: 100px"
                    :style="
                      deviceInfo[dock.sn] && deviceInfo[dock.sn].mode_code !== EModeCode.Disconnected
                        ? 'color: #00ee8b'
                        : 'color: red;'
                    "
                  >
                    {{
                      deviceInfo[dock.sn]
                        ? EModeCodeStatus[deviceInfo[dock.sn].mode_code]
                        : EModeCodeStatus[EModeCode.Disconnected]
                    }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getDeviceTopo, getUnreadDeviceHms, updateDeviceHms } from '@/api/manage'
import noData from '@/assets/icons/no-data.png'
import { useMyStore } from '@/store'
import { EDeviceTypeName, ELocalStorageKey } from '@/types'
import { EDockModeCode, EDockModeCodeStatus, EModeCode, EModeCodeStatus, OnlineDevice } from '@/types/device'
import { EHmsLevel, ERouterName } from '@/types/enums'
import { DoubleRightOutlined, EyeInvisibleOutlined, EyeOutlined, RobotOutlined, RocketOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Plus } from 'lucide-vue-next'
import { sessionStorage } from '@/utils/storage'

const route = useRoute()

const taskRoute = computed(() => {
  return route.name === ERouterName.TASK
})
const store = useMyStore()
const username = ref(sessionStorage.get(ELocalStorageKey.Username))
const workspaceId = ref(sessionStorage.get(ELocalStorageKey.WorkspaceId)!)
const osdVisible = computed(() => store.state.osdVisible)
const hmsVisible = new Map<string, boolean>()
const scorllHeight = ref()

const onlineDevices = reactive({
  data: [] as OnlineDevice[]
})

const onlineDocks = reactive({
  data: [] as OnlineDevice[]
})

const deviceInfo = computed(() => store.state.deviceState.deviceInfo)
const dockInfo = computed(() => store.state.deviceState.dockInfo)
const hmsInfo = computed({
  get: () => store.state.hmsInfo,
  set: (val) => {
    return val
  }
})

onMounted(() => {
  getOnlineTopo()
  setTimeout(() => {
    watch(
      () => store.state.deviceStatusEvent,
      (data) => {
        getOnlineTopo()
        if (data.deviceOnline.sn) {
          getUnreadHms(data.deviceOnline.sn)
        }
      },
      {
        deep: true
      }
    )
    getOnlineDeviceHms()
  }, 3000)
  const element = document.getElementsByClassName('scrollbar').item(0) as HTMLDivElement
  const parent = element?.parentNode as HTMLDivElement
  scorllHeight.value = parent?.clientHeight - parent!.firstElementChild!.clientHeight
})

function getOnlineTopo() {
  getDeviceTopo(workspaceId.value).then((res) => {
    if (res.code !== 1) {
      return
    }
    onlineDevices.data = []
    onlineDocks.data = []
    res.data.forEach((gateway: any) => {
      const child = gateway.children
      const device: OnlineDevice = {
        model: child?.device_name,
        callsign: child?.nickname,
        sn: child?.device_sn,
        mode: EModeCode.Disconnected,
        gateway: {
          model: gateway?.device_name,
          callsign: gateway?.nickname,
          sn: gateway?.device_sn,
          domain: gateway?.domain
        },
        payload: []
      }
      child?.payloads_list.forEach((payload: any) => {
        device.payload.push({
          index: payload.index,
          model: payload.model,
          payload_name: payload.payload_name,
          payload_sn: payload.payload_sn,
          control_source: payload.control_source,
          payload_index: payload.payload_index
        })
      })
      if (EDeviceTypeName.Dock === gateway.domain) {
        hmsVisible.set(device.sn, false)
        hmsVisible.set(device.gateway.sn, false)
        onlineDocks.data.push(device)
      }
      if (gateway.status && EDeviceTypeName.Gateway === gateway.domain) {
        onlineDevices.data.push(device)
      }
    })
  })
}

function switchVisible(e: any, device: OnlineDevice, isDock: boolean, isClick: boolean) {
  if (!isClick) {
    e.target.style.cursor = 'not-allowed'
    return
  }
  if (device.sn === osdVisible.value.sn) {
    osdVisible.value.visible = !osdVisible.value.visible
  } else {
    osdVisible.value.sn = device.sn
    osdVisible.value.callsign = device.callsign
    osdVisible.value.model = device.model
    osdVisible.value.visible = true
    osdVisible.value.gateway_sn = device.gateway.sn
    osdVisible.value.is_dock = isDock
    osdVisible.value.gateway_callsign = device.gateway.callsign
    osdVisible.value.payloads = device.payload
  }
  store.commit('SET_OSD_VISIBLE_INFO', osdVisible)
}

function getUnreadHms(sn: string) {
  getUnreadDeviceHms(workspaceId.value, sn).then((res) => {
    if (res.data.length !== 0) {
      hmsInfo.value[sn] = res.data
    }
  })
  console.info(hmsInfo.value)
}

function getOnlineDeviceHms() {
  const snList = Object.keys(dockInfo.value)
  if (snList.length === 0) {
    return
  }
  snList.forEach((sn) => {
    getUnreadHms(sn)
  })
  const deviceSnList = Object.keys(deviceInfo.value)
  if (deviceSnList.length === 0) {
    return
  }
  deviceSnList.forEach((sn) => {
    getUnreadHms(sn)
  })
}

function readHms(visiable: boolean, sn: string) {
  if (!visiable) {
    updateDeviceHms(workspaceId.value, sn).then((res) => {
      if (res.code === 1) {
        delete hmsInfo.value[sn]
      }
    })
  }
}

function openLivestreamOthers() {
  store.commit('SET_LIVESTREAM_OTHERS_VISIBLE', true)
}

function openLivestreamAgora() {
  store.commit('SET_LIVESTREAM_AGORA_VISIBLE', true)
}
</script>

<style lang="scss">
.route-icon {
  color: #fff;
  font-size: 16px;
}
.online {
  background: rgba(219, 219, 219, 0.06);
  font-size: 13px;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid rgba(219, 219, 219, 0.4);
}
</style>
